package com.huantai.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.huantai.gateway.bean.BaseResponse;
import com.huantai.gateway.util.JWTUtil;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import wiremock.org.eclipse.jetty.util.StringUtil;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import static com.huantai.gateway.constant.Const.HEADER_TOKEN_KEY;

@Component
@Log4j2
@Configuration
@RefreshScope
@Data
public class AuthFilter implements GlobalFilter, Ordered {

    @Value("#{'${auth.ignore.urls}'.split(',')}")
    private List<String> ignoreUrls = new ArrayList<>();

    @Autowired
    JWTUtil jwtUtil;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String url = exchange.getRequest().getURI().getPath();

        //忽略以下url请求
        if (ignoreUrls.contains(url)) {
            return chain.filter(exchange);
        }

        //从请求头中取得token
        String token = exchange.getRequest().getHeaders().getFirst(HEADER_TOKEN_KEY);
        if (StringUtil.isEmpty(token)) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.OK);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");

            BaseResponse res = new BaseResponse("401", "401 unauthorized");
            byte[] responseByte = JSONObject.toJSON(res).toString().getBytes(StandardCharsets.UTF_8);

            DataBuffer buffer = response.bufferFactory().wrap(responseByte);
            return response.writeWith(Flux.just(buffer));
        }

        // 验证token是否合法
        boolean verifyResult = jwtUtil.verify(token);
        if (!verifyResult) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.OK);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");

            BaseResponse res = new BaseResponse("1004", "invalid token");
            byte[] responseByte = JSONObject.toJSON(res).toString().getBytes(StandardCharsets.UTF_8);

            DataBuffer buffer = response.bufferFactory().wrap(responseByte);
            return response.writeWith(Flux.just(buffer));
        }

        // 检查头信息用户是否匹配
        //String user = jwtUtil.getUser(token);

        return chain.filter(exchange);
    }


    @Override
    public int getOrder() {
        return -100;
    }
}